package com.addzero.web

import androidx.compose.runtime.*
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.input.key.*
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import com.addzero.SpringBootApp.Companion.runSpringBootApp
import com.addzero.web.ui.system.animation.UseSplashScreen
import com.addzero.web.ui.system.layout.MainLayout
import com.addzero.web.ui.system.theme.AppTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.ConcurrentHashMap

val loggerMap = ConcurrentHashMap<Class<*>, Logger>()
inline val <reified T> T.log: Logger get() = loggerMap.computeIfAbsent(T::class.java) { LoggerFactory.getLogger(it) }


@OptIn(ExperimentalComposeUiApi::class)
fun main(args: Array<String>) {
    //ksp生成版dsl
    application {
        val useSplashScreen = UseSplashScreen(
            { MainLayout() }
        )
        // 在协程中启动后端服务
        val scope = CoroutineScope(Dispatchers.IO)
        scope.launch {
            runSpringBootApp(args)
            useSplashScreen.showAnimation = false
        }

        val windowState = rememberWindowState(
            width = 1200.dp, height = 800.dp
        )
        
        // 界面刷新状态
        var refreshKey by remember { mutableStateOf(0) }

        Window(
            onCloseRequest = ::exitApplication, 
            title = "compose desktop", 
            state = windowState,
            onPreviewKeyEvent = { keyEvent ->
                // 监听F5按键，用于刷新界面
                if (keyEvent.type == KeyEventType.KeyDown && 
                    keyEvent.key == Key.F5) {
                    log.info("检测到F5按键，刷新界面")
                    refreshKey++ // 通过更改状态变量触发界面重组
                    return@Window true
                }
                // 监听Ctrl+R组合键，作为刷新的替代选项
                if (keyEvent.type == KeyEventType.KeyDown && 
                    keyEvent.isCtrlPressed && 
                    keyEvent.key == Key.R) {
                    log.info("检测到Ctrl+R组合键，刷新界面")
                    refreshKey++
                    return@Window true
                }
                false
            }
        ) {
            // 使用key参数强制组合项重组
            key(refreshKey) {
                AppTheme {
                    useSplashScreen.render {}
                }
            }
        }
    }
}
